import request from '@/utils/request';
import URLS from './APIUrlDefine';
import {CURRENT_TOKEN} from '@/components/Authorized/renderAuthorize';


interface LoginParams {
  userName: string;
  password: string;
  type: string;
}

export async function query(): Promise<any> {
  return request('/api/users');
}

/**
 * 获取用户列表
 * @param data
 */
export async function GetUserList(data: any): Promise<any> {
  // console.log(data);
  return request(`${URLS.GET_USER_LIST}/${data.current}/${data.pageSize}`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  }).then((response) => {
    const data = response.data;
    const result = {
      data: data.records,
      total: data.total,
      success: true,
      pageSize: data.size,
      current: parseInt(`${data.current}`, 10) || 1,
    };
    return Promise.resolve(result);
  });
}

/**
 * 获取角色列表
 * @param data
 */
export async function GetRoleList(data: any): Promise<any> {
  // console.log(data);
  return request(`${URLS.GET_ROLER_LIST}/${data.current}/${data.pageSize}`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  }).then((response) => {
    const data = response.data;
    const result = {
      data: data.records,
      total: data.total,
      success: true,
      pageSize: data.size,
      current: parseInt(`${data.current}`, 10) || 1,
    };
    return Promise.resolve(result);
  });
}

/**
 * 创建新的角色信息
 * @param data
 */
export async function CreateNewRole(data: {
  desc: string;
  name: string;
  isDef: number;
  pers?: Array<number>;
}) {
  return request(`${URLS.CREATE_NEW_ROLE}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: data,
  });
}

/**
 * 修改角色权限
 * @param pres
 */
export async function UpdateRole(data: any) {
  return request(`${URLS.CREATE_NEW_ROLE}`, {
    method: 'PUT',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: data,
  });
}

/**
 * 根据id删除指定角色
 * @param id
 */
export async function DeleteRole(id: number) {
  return request(`${URLS.DELETE_ROLE}/${id}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  });
}

/**
 * 根据id删除指定用户
 * @param id
 */
export async function DeleteUser(id: number) {
  return request(`${URLS.DELETE_USER}/${id}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  });
}

export async function GetOnlyPermissionList() {
  // console.log(data);
  return request(`${URLS.GET_PERMISSION_Tree}/1/9999`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${CURRENT_TOKEN}`,
      },
    }
  );
}


export async function GetPermissionList(data: any): Promise<any> {
  // console.log(data);
  return request(`${URLS.GET_PERMISSION_Tree}/${data.current}/${data.pageSize}`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  }).then((response) => {
    const data = response.data;
    const result = {
      data: data.records,
      total: data.total,
      success: true,
      pageSize: data.size,
      current: parseInt(`${data.current}`, 10) || 1,
    };
    return Promise.resolve(result);
  });
}

export async function CreateNewPermission(data: any) {
  return request(`${URLS.CREATE_NEW_PERMISSION}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: data,
  });
}

export async function UpdatePermission(data: any) {
  return request(`${URLS.UPDATE_PERMISSION}`, {
    method: 'PUT',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: data,
  });
}

export async function DeletePermission(id: number) {
  return request(`${URLS.DELETE_PERMISSION}/${id}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  });
}

export async function UserLogin(params: LoginParams): Promise<any> {
  // var parm =
  //   'client_id=test&client_secret=123456&grant_type=password&' +
  //   'username=' +
  //   params.userName +
  //   '&password=' +
  //   params.password;

  var token = '';
  return request(URLS.USER_LOGIN, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    data: params,
  })
    .then(async (res) => {
      if (res.hasOwnProperty("data") && res.data.hasOwnProperty("access_token")) {
        //登录成功
        token = res.data.access_token;
        try {
          let result = await request(URLS.GET_CURRENT_USER, {
            method: 'GET',
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });
          return Promise.resolve({
            access_token: token,
            permissions: result.data.permissions,
          })
        } catch (e) {
          return Promise.reject({
            access_token: undefined,
            permissions: [],
          });
        }
      } else {
        //登录失败
        return Promise.reject({
          access_token: undefined,
          permissions: [],
        }).catch((e) => {
          console.log(e);
        });
      }
    })

}

export async function GetCurrentUser(): Promise<any> {
  return request(URLS.GET_CURRENT_USER, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
  });
}


export async function ChangeUserState(data: any): Promise<any> {
  return request(URLS.CHANGE_USER_STATE, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
    params: data
  });
}

export async function ChangeRoleState(data: any): Promise<any> {
  return request(URLS.CHANGE_ROLE_STATE, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
    params: data
  });
}


export async function ChangePermissionState(data: any): Promise<any> {
  return request(URLS.CHANGE_PERMISSION_STATE, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
    params: data
  });
}

export async function SearchPermission(data: any): Promise<any> {
  return request(URLS.SEARCH_PERMISSION + "?key=" + data || "", {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${CURRENT_TOKEN}`,
    },
    params: data
  }).then((res) => res.data);
}
